package com.explorati.LeetCode22.getKthFromEnd;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 18:39 2020/9/13 0013
 * @ Description ：
 */
public class Solution {
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    /**
     * 给定一个链表: 1->2->3->4->5, 和 k = 2.
     * 返回链表 4->5.
     * @param head
     * @param k
     * @return
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
        //先遍历一遍链表，获取有多少元素
        //然后在遍历一遍，当前节点为size()-1 == k时返回
        int size = 1;
        ListNode cur = head;
        while(cur != null) {
            size ++;
            cur = cur.next;
        }

        while(head != null && size - 1 != k) {
           head = head.next;
           size --;
        }
        return head;
    }
}
